<template>
  <div class="app-container">
    <div class="panel-search">
      <el-form :model="searchData" ref="searchForm" :inline="true">
        <el-form-item label="消息内容">
          <el-input v-model="searchData.searchableKey" placeholder="请输入消息内容" @keyup.enter.native="onSearch" clearable />
        </el-form-item>
        <el-form-item label="时间">
          <el-date-picker
            v-model="searchData.range"
            type="daterange"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            style="width: 280px"
            value-format="yyyy-MM-dd"
          />
        </el-form-item>
        <el-form-item label="会话类型">
          <el-select v-model="searchData.type" placeholder="请选择" style="width: 150px" @change="onTypeChange">
            <el-option label="群聊" value="群聊" />
            <el-option label="单聊" value="单聊" />
          </el-select>
        </el-form-item>
        <el-form-item label="消息类型">
          <el-select v-model="searchData.contentType" placeholder="请选择" style="width: 180px" @change="onContentTypeChange">
            <el-option label="文本" value="文本" />
            <el-option label="图片" value="图片" />
            <el-option label="视频" value="视频" />
            <el-option label="语音" value="语音" />
            <el-option label="文件" value="文件" />
          </el-select>
        </el-form-item>
        <el-form-item label="发送者昵称">
          <el-input v-model="searchData.senderName" placeholder="请输入发送者昵称" style="width: 180px" clearable />
        </el-form-item>
        <el-form-item label="接收者昵称">
          <el-input v-model="searchData.receiverName" placeholder="请输入接收者昵称" style="width: 230px" clearable />
        </el-form-item>
        <el-form-item label="发送者ID">
          <el-input v-model="searchData.senderId" placeholder="请输入发送者ID" style="width: 220px" clearable />
        </el-form-item>
        <el-form-item label="接收者ID">
          <el-input v-model="searchData.receiverId" placeholder="请输入接收者ID" style="width: 180px" clearable />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="onSearch">查询</el-button>
          <el-button @click="onReset">重置</el-button>
        </el-form-item>
      </el-form>
    </div>

    <div class="panel-table">
      <div class="panel-table-tool">
        <el-button type="primary" plain @click="onDelete()">批量删除</el-button>
        <el-button type="primary" plain @click="onExport">导出</el-button>
      </div>

      <el-table
        :data="tableData.data"
        border
        v-loading="tableData.loading"
        @selection-change="onSelectionChange"
      >
        <el-table-column type="selection" width="50" align="center" />
        <el-table-column label="序号" type="index" width="50" align="center" />
        <el-table-column label="会话类型" prop="sessionType" width="75px" align="center">
          <template slot-scope="scope">
            {{ scope.row.sessionType === 0 ? '单聊' : '群聊' }}
          </template>
        </el-table-column>
        <el-table-column label="消息类型" prop="messageType" width="75px" align="center">
          <template slot-scope="scope">
            <el-tag :type="getMessageTypeColor(scope.row.messageType)">
              {{ getMessageTypeText(scope.row.messageType) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="发送者昵称" prop="senderNickname" width="100px" align="center" />
        <el-table-column label="接收者昵称" prop="receiverNickname" width="130px" align="center" />
        <el-table-column label="发送者ID" prop="senderId"  align="center" />
        <el-table-column label="接收者ID" prop="receiverId"  align="center" />
        <el-table-column label="消息内容" prop="content" align="center">
          <template slot-scope="scope">
            <div v-if="scope.row.messageType === 1">{{ scope.row.content }}</div>
            <div v-else-if="scope.row.messageType === 2 || scope.row.messageType === 23">
              <el-button type="text" @click="onPlayAmr(scope.row)">播放语音</el-button>
            </div>
            <div v-else-if="scope.row.messageType === 3 || scope.row.messageType === 7">
              <el-image
                style="width: 50px; height: 50px"
                :src="scope.row.content"
                :preview-src-list="[scope.row.content]">
              </el-image>
            </div>
            <div v-else-if="scope.row.messageType === 6">
              <video
                :src="scope.row.content"
                controls
                style="max-width: 200px">
              </video>
            </div>
            <div v-else-if="scope.row.messageType === 5">
              <a :href="scope.row.content" target="_blank" class="file-name">{{ scope.row.fileName }}</a>
            </div>
          </template>
        </el-table-column>
        <el-table-column label="时间" prop="createdAt" align="center" width="180" />
        <el-table-column label="操作" align="center" width="120px">
          <template slot-scope="scope">
            <el-button type="text" size="small" @click="onView(scope.row)">查看</el-button>
            <el-button type="text" size="small" @click="onDelete(scope.row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>

      <pagination
        v-show="pagerData.total>0"
        :total="pagerData.total"
        :page.sync="pagerData.current"
        :limit.sync="pagerData.pageSize"
        @pagination="queryTableList"
      />
    </div>

    <!-- 查看详情弹窗 -->
    <message-manage-detail
      v-if="modalData.showDetail"
      :modalParam="modalData.data"
      @close="closeModal('showDetail', $event)">
    </message-manage-detail>
  </div>
</template>

<script>
import MessageManageDetail from "@/views/chat/message/MessageManageDetail.vue";
import BenzAMRRecorder from 'benz-amr-recorder';
import { deleteMessageById, queryMessageList } from '@/api/chat/message'
import { delPost } from '@/api/system/post'

export default {
  components: {
    MessageManageDetail
  },
  data() {
    return {
      searchData: {
        senderName: '',
        receiverName: '',
        senderId: '',
        receiverId: '',
        type: null,
        searchableKey: '',
        contentType: '',
        pageNum: 1,
        pageSize: 10,
        range: []
      },
      modalData: {
        showDetail: false,
        data: null
      },
      orgList: [],
      tableData: {
        loading: false,
        data: [],
      },
      //选中的消息
      selectedRowKeys: [],
      pagerData: {
        current: 1, pageSize: 10, total: 0
      },
      total: 0
    }
  },
  created() {
    // 获取传递的消息类型参数
    const messageType = this.$route.query.messageType;
    console.log("messageType是：：：："+messageType);
    // 设置消息类型单选框的选中状态
    if (messageType) {
      switch (messageType) {
        case 'text':
          this.searchData.contentType = '文本';
          break;
        case 'voice':
          this.searchData.contentType = '语音';
          break;
        case 'image':
          this.searchData.contentType = '图片';
          break;
        case 'video':
          this.searchData.contentType = '视频';
          break;
      }

      // 触发查询操作，根据需要调用对应的查询方法
      this.queryInfoData(messageType); // 请替换成实际的查询方法
    }
    this.queryPageData();
    console.log("成功调用mounted方法");

  },

  methods: {
    queryMessageList,

    onPlayAmr(url){
      var amr = new BenzAMRRecorder()
      amr.initWithUrl(url).then(function() {
        amr.play()
      })
      amr.onEnded(function() {
        //alert('播放完毕')
      })
    },
    //获取页面数据
    queryPageData() {
      this.queryTableList();
    },
    //获取表格数据
    queryTableList() {
      // 构建请求参数
      let params = {
        senderName: this.searchData.senderName,
        receiverName: this.searchData.receiverName,
        senderId: this.searchData.senderId,
        receiverId: this.searchData.receiverId,
        searchableKey: this.searchData.searchableKey,
        pageNum: this.pagerData.current,
        pageSize: this.pagerData.pageSize,
        type:this.searchData.type,
        contentType: this.getContentType(this.searchData.contentType),
        begin:null,
        end:null,
      };

      // 添加类型和消息类型的判断，如果不为空 则加入请求参数
      if (this.searchData.type !== null) {
        params.type = this.searchData.type === '群聊' ? 1 : 0;
      }

      // 处理日期时间范围
      if (this.searchData.range) {
        params.begin = this.formatDate(this.searchData.range[0]) ;
        params.end = this.formatDate(this.searchData.range[1]) ;
      }
      // 过滤出非空参数
      params = Object.fromEntries(Object.entries(params).filter(([key, value]) => value !== undefined && value !== null));
      this.tableData.loading = true;
      queryMessageList(params).then(res => {
        if(res.code == 200) {
          //设置表格数据
          this.tableData.data = res.rows.map(msg => ({
            tableName: msg.tableName,
            sessionType: msg._type,
            messageType: msg._content_type,
            senderNickname: msg.sender_name,
            receiverNickname: msg.receiver_name,
            senderId: msg.sender_uid,
            receiverId: msg.receiver_uid,
            content: msg._searchable_key,
            createdAt: msg._dt,
            id: msg._mid+'',
            mid: msg.midstr,
            fileName:msg.fileName
          }));
          //设置分页数据
          this.pagerData.total = res.total;
        }
      }).finally(() => {
        this.tableData.loading = false;
      })
      console.log(this.tableData.data);
    },

    //查询
    onSearch() {
      this.pagerData.current = 1;
      this.queryTableList();
    },

    //重置搜索条件
    onReset() {
      // 将 searchData 对象中的属性重置为初始值
      this.searchData.senderName = '';
      this.searchData.receiverName = '';
      this.searchData.senderId = '';
      this.searchData.receiverId = '';
      this.searchData.type = null;
      this.searchData.searchableKey = '';
      this.searchData.contentType = null;
      this.searchData.page = 1;
      this.searchData.pageSize = 10;
      this.searchData.begin = null;
      this.searchData.end = null;
      this.searchData.range = null;
      this.onSearch();
    },

    // 多选框选中数据
    onSelectionChange(selection) {
      this.selectedRowKeys = selection.map(item => item.id)
    },
    onView(record) {
      const messageId = record.mid;
      this.modalData.showDetail = false;
      this.$nextTick(() => {
        this.modalData.data = {
          modalTitle: "查看",
          messageId: messageId, // 将消息的唯一标识传递给 modalData
        };
        this.modalData.showDetail = true;
      });
    },

    onDelete(record) {
      let message = [];
      if (record) { // 单个删除
        //把信息的属于哪张表的序号给拼到Id的后面
        let third = record.tableName.split("_")[2];
        message.push(record.mid+"_"+third)
      } else { // 批量删除
        let selectedRows = _.filter(this.tableData.data, o => {
          return _.includes(this.selectedRowKeys, o.id);
        });
        selectedRows.forEach(item =>{
          message.push(item.mid+"_"+item.tableName.split("_")[2])
        })
      }
      if (message.length <= 0) {
        this.$modal.alertWarning("请选择要删除的消息！");
        return;
      }

      let params = {
         ids: _.join(message, ","),
      };
      this.$modal.confirm('是否确认删除消息ID为'+message +'的数据项?').then(function() {
        return deleteMessageById(params);
      }).then(() => {
        this.onSearch();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    },


    // 实现导出功能
    onExport() {
      // 构建请求参数
      let params = {
        senderName: this.searchData.senderName,
        receiverName: this.searchData.receiverName,
        senderId: this.searchData.senderId,
        receiverId: this.searchData.receiverId,
        searchableKey: this.searchData.searchableKey,
        pageNum: this.pagerData.current,
        pageSize: this.pagerData.pageSize,
        type:this.searchData.type,
        contentType: this.getContentType(this.searchData.contentType),
        begin:null,
        end:null,
      };
      // 添加类型和消息类型的判断，如果不为空 则加入请求参数
      if (this.searchData.type !== null) {
        params.type = this.searchData.type === '群聊' ? 1 : 0;
      }
      // 处理日期时间范围
      if (this.searchData.range) {
        params.begin = this.formatDate(this.searchData.range[0]) ;
        params.end = this.formatDate(this.searchData.range[1]) ;
      }
      // 过滤出非空参数
      params = Object.fromEntries(Object.entries(params).filter(([key, value]) => value !== undefined && value !== null));
      this.download('chat/export', {
        ...params
      }, `消息列表_${this.formatDateForFileName(new Date().getTime())}.xlsx`)
    },
    //关闭弹窗
    closeModal(type, data) {
      this.modalData.data = null;
      this.modalData[type] = false;
      if (data && data.refresh) {
        this.onSearch();
      }
    },
    getContentType(type){
      if(!type){
        return null;
      }
      switch (type){
        case '文本':
          return '1';
          break;
        case '图片':
          return '3,7';
          break;
        case '视频':
          return '6';
          break;
        case '语音':
          return '2,23';
          break;
        case '文件':
          return '5';
          break;
      }
    },
    // 格式化日期的辅助方法
    formatDate(dateString) {
      if (dateString) {
        const date = new Date(dateString);
        const year = date.getFullYear();
        const month = (date.getMonth() + 1).toString().padStart(2, '0');
        const day = date.getDate().toString().padStart(2, '0');
        return `${year}-${month}-${day}`;
      } else {
        return null;
      }
    },
    formatDateForFileName(dateString) {
      const date = new Date(dateString);
      const year = date.getFullYear();
      const month = String(date.getMonth() + 1).padStart(2, '0'); // 月份从0开始
      const day = String(date.getDate()).padStart(2, '0');
      const hours = String(date.getHours()).padStart(2, '0');
      const minutes = String(date.getMinutes()).padStart(2, '0');
      const seconds = String(date.getSeconds()).padStart(2, '0');

      return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
    },
    // 添加获取消息类型颜色的方法，你可以根据实际需求自定义颜色逻辑
    getMessageTypeColor(type) {
      switch (type) {
        case 1:
          return 'blue';
        case 2:
        case 23:
          return 'green';
        case 5:
          return 'cyan';
        case 3:
        case 7:
          return 'red';
        case 6:
          return 'purple';
        default:
          return 'blue';
      }
    },
    // 添加获取消息类型文本的方法，你可以根据实际需求自定义文本逻辑
    getMessageTypeText(type) {
      switch (type) {
        case 1:
          return '文本';
        case 2:
        case 23:
          return '语音';
        case 5:
          return '文件';
        case 3:
        case 7:
          return '图片';
        case 6:
          return '视频';
        default:
          return '文本';
      }
    },

//已有消息类型进行查询
    queryInfoData(messageType){
      // 构建请求参数
      let params = {
        senderName: this.searchData.senderName,
        receiverName: this.searchData.receiverName,
        senderId: this.searchData.senderId,
        receiverId: this.searchData.receiverId,
        searchableKey: this.searchData.searchableKey,
        page: this.pagerData.current,
        pageSize: this.pagerData.pageSize,
        type:this.searchData.type,
        contentType:messageType,
        begin:null,
        end:null,
      };

      // 添加类型和消息类型的判断，如果不为空 则加入请求参数
      if (this.searchData.type !== null) {
        params.type = this.searchData.type === '群聊' ? 1 : 0;
      }

      //if (this.searchData.contentType !== null) {
      switch (messageType) {
        case 'text':
          params.contentType = 1;
          break;
        case 'voice':
          params.contentType = 2;
          break;
        case 'image':
          params.contentType = 3;
          break;
        case 'video':
          params.contentType = 4;
          break;
        default:
          params.contentType = 1; // 默认为文本类型
      }
      // 处理日期时间范围
      if (this.searchData.range) {
        params.begin = this.formatDate(this.searchData.range[0]) ;
        params.end = this.formatDate(this.searchData.range[1]) ;
      }
      // 过滤出非空参数
      params = Object.fromEntries(Object.entries(params).filter(([key, value]) => value !== undefined && value !== null));
      // 构建 URL 字符串
      // let url = `${this.$Api.messageData.queryMessageList}?${new URLSearchParams(params).toString()}`;
      this.tableData.loading = true;
      //this.$ajax.get(this.$Api.messageData.queryMessageList, params).then(res => {
      queryMessageList(params).then(res => {
        if(res.code == 200) {
          console.log('res================',res)
          //设置表格数据
          this.tableData.data = res.rows.map(msg => ({
            sessionType: msg._type,
            messageType: msg._content_type,
            senderNickname: msg.sender_name,
            receiverNickname: msg.receiver_name,
            senderId: msg.sender_uid,
            receiverId: msg.receiver_uid,
            content: msg._searchable_key,
            createdAt: msg._dt,
            id: msg._mid+'',
            mid: msg.midstr
          }));
          //设置分页数据
          this.pagerData.total = res.total;
        }
      }).finally(() => {
        this.tableData.loading = false;
      })
    },

    // 会话类型下拉框变化事件处理
    onTypeChange() {
      this.pagerData.current = 1;
      this.queryTableList();
    },

    // 消息类型下拉框变化事件处理
    onContentTypeChange() {
      this.pagerData.current = 1;
      this.queryTableList();
    },
  }
}
</script>

<style lang="scss" scoped>
.app-container {
  padding: 20px;

  .panel-search {
    margin-bottom: 20px;
    padding: 20px;
    background: #fff;
    border-radius: 4px;
  }

  .panel-table {
    background: #fff;
    padding: 20px;
    border-radius: 4px;

    .panel-table-tool {
      margin-bottom: 20px;
    }
  }
}
</style>
